package com.adingxiong.cft.util;



import com.adingxiong.cft.common.entity.DDuser;
import com.adingxiong.cft.errors.Assert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Builder;
import lombok.Data;
import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName HttpUtils
 * @Description   Http 请求第三方接口工具类
 * @Author xiongchao
 * @Date 2020/7/29 16:33
 **/
public class HttpUtils {

    public static final MediaType JSON  = MediaType.get("application/json;charset=utf-8");


    private static OkHttpClient client = new OkHttpClient();

    public static String doGet (String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        return getResponse(request);
    }

    private static String getResponse(Request request) {
        try {
            Response res = client.newCall(request).execute();
            return res.body().string();
        } catch (Exception e){
            Assert.fail("request_error");
            return null;
        }
    }

    //Post请求

    public static String doPost (String url ,String json) {
        RequestBody body = RequestBody.create(JSON,json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return getResponse(request);
    }

    /**
     *  下载网络资源到本地
     * @param urlString
     * @param filename
     * @param savePath
     * @throws Exception
     */
    private void download(String urlString, String filename,String savePath) throws Exception {
        URL url = new URL(urlString);
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File(savePath);
        if(!sf.exists()){
            sf.mkdirs();
        }
        String extensionName = urlString.substring(urlString.lastIndexOf("."));
        String newFileName = filename + extensionName;
        OutputStream os = new FileOutputStream(sf.getPath()+File.separator+newFileName);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        ZipUtils.close(os,is);
    }


    public static List<DDuser> getDDList() {
    //public static void main(String[] args) {

        String AgentId = "1206061124";
        String AppKey ="dingyttnxxea0zb7ozig";
        String AppSecret ="P8BN3D1a4I1VpHqA4XVYhjDECUtyMpOyXyRB_xC_MsK3t9eRbG2BCyZ_Uz3niefZ";

        String get_token ="https://oapi.dingtalk.com/gettoken?appkey=dingyttnxxea0zb7ozig&appsecret=P8BN3D1a4I1VpHqA4XVYhjDECUtyMpOyXyRB_xC_MsK3t9eRbG2BCyZ_Uz3niefZ";
        String get_DepartList = "https://oapi.dingtalk.com/department/list";
        String saveUser = "https://oapi.dingtalk.com/user/create";

        String getList = "https://oapi.dingtalk.com/user/simplelist";


        //获取token
        String s = doGet(get_token);
        JSONObject parse = (JSONObject) JSONObject.parse(s);

        Integer code = (Integer) parse.get("errcode");
        if(code.equals(0)){
            String  token = (String) parse.get("access_token");


            String depUrl = get_DepartList + "?access_token=" + token;
            //获取部门列表

            String s1 = doGet(depUrl);
            JSONObject deps = (JSONObject) JSONObject.parse(s1);


            JSONArray depList = (JSONArray) deps.get("department");
            JSONObject o = (JSONObject) depList.get(0);
            Integer id = (Integer) o.get("id");


            //新建用户

            UserInfo userInfo = UserInfo.builder()
                    .department(Arrays.asList(id.toString().split(",")))
                    .name("熊超测试")
                    .mobile("15071384121")
                    .build();

            String url = saveUser + "?access_token=" + token;
            String par = JSONObject.toJSONString(userInfo);
            String s2 = doPost(url, par);


            //查询用户列表
            String listUrl = getList  + "?access_token=" + token + "&department_id=" + id;

            String listStr = doGet(listUrl);
            Result result = JSONObject.parseObject(listStr, Result.class);
            if(result.getErrcode().equals(0)) {
                return result.getUserlist();
            }


        }


        return null;



    }

    @Data
    @Builder
    static  class UserInfo {
        private String mobile;

        private List<String> department;

        private String name ;

    }

    @Data
    static class Result {
        Integer errcode;

        String errmsg;

        List<DDuser> userlist;
    }
}
